package com.sl.au.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.Attachment;
import com.sl.au.entity.Saleman;
import com.sl.au.service.SalemanService;

/**
 * 销售人员管理控制器
 * @author XH
 *
 */
@RestController
@RequestMapping(value = "/ui/saleman")
public class SalemanController extends BaseController {

	@Autowired
	SalemanService salemanService;

	/**
	 * 页面显示
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index() {
		ModelAndView modelAndView = this.createLayoutView("saleman/salemanindex");

		return modelAndView;
	}

	/**
	 * 获取页面数据
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getpage", method = RequestMethod.GET)
	public Map<String, Object> getPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		String findKey='%'+key+'%';
		List<Saleman> salemans = null;
		Long count = null;
		//判断是否有查询字段
		if (StringUtils.hasText(key)) {
			salemans = salemanService.getSalemans(start, length, findKey, null, null);
			count = (long) salemans.size();
		} else {
			salemans = salemanService.getPage(start, length, null, null, null);
			count = salemanService.getRepository().count();
			
		}
		map.put("data", salemans);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	//删除销售人员
	@RequestMapping(value = "delSaleman", method = RequestMethod.GET)
	public Map<String, Object> delSaleman(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String ids = request.getParameter("ids");
		String id[] = ids.split(",");
		List<Saleman> salemans = new ArrayList<Saleman>();
		for (int i = 0; i < id.length; i++) {
			String salemanId = id[i];
			Saleman saleman = new Saleman();
			saleman.setId(salemanId);
			salemans.add(saleman);
		}
		salemanService.getRepository().deleteInBatch(salemans);
		map.put("code", 0);
		return map;
	}

}
